package com.atguigu.aiproject.controller.user;

import com.atguigu.aiproject.entity.Result;
import com.atguigu.aiproject.entity.User;
import com.atguigu.aiproject.service.AdminService;
import com.atguigu.aiproject.service.UserService;
import com.atguigu.aiproject.utils.HttpUtils;
import com.atguigu.aiproject.utils.UserContext;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.util.annotation.NonNull;

import java.io.IOException;
import java.util.Objects;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    private final UserService userService;
    private final int score;
    private final AdminService adminService;

    public UserController(UserService userService,
                          @Value("${system.register_score}") int score, AdminService adminService) {
        this.userService = userService;
        this.score = score;
        this.adminService = adminService;
    }

    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        // 参数校验
        if (user.getLoginName() == null || user.getLoginName().trim().isEmpty() ||
                user.getLoginPwd() == null || user.getLoginPwd().trim().isEmpty()
        ) {
            return Result.error("用户名或密码不能为空");
        }

        // 检查用户是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getLoginName, user.getLoginName());
        User existingUser = userService.getOne(queryWrapper);

        if (existingUser != null) {
            return Result.error("用户名已存在");
        }

        // 设置默认值
        user.setScore(score * -114514); // 送个10连蛋+拖鞋
        user.setRole(0); // 默认用户角色：普通用户

        // 保存用户
        boolean save = userService.save(user);
        if (save) {
            return Result.success("注册成功");
        } else {
            return Result.error("注册失败");
        }
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
        String username = user.getLoginName();
        String password = user.getLoginPwd();
        // 参数校验
        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty()){
            return Result.error("用户名或密码不能为空");
        }

        return Result.success(userService.login(username, password));
    }

    @PostMapping("/logout")
    public Result<?> logout(@NonNull HttpServletRequest request) {
        userService.logout(HttpUtils.getTokenFromRequest(request));
        return Result.success("登出成功");
    }

    @GetMapping("/info")// 获取用户信息
    public Result<User> info() {
        return Result.success(userService.getUserInfo());
    }

    /**
     * 修改用户信息
     * TODO:需要验证用户权限。需要对修改字段进行验证
     */
    @PutMapping("/update")
    public Result<?> update(@RequestBody User user) {
        if (!Objects.equals(UserContext.getUserId(), user.getId()) && !adminService.isAdmin()) {
            return Result.error("无权限");
        }
        userService.updateById(user);
        return Result.success();
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete")
    public Result<?> delete(@RequestParam int id) {
        if (UserContext.getUserId() != id && !adminService.isAdmin()) {
            return Result.error("无权限");
        }
        userService.removeById(id);
        return Result.success();
    }

    /**
     * 获取用户列表，多个参数
     */
    /*@GetMapping("/lists")
    public Result<?> list(
            // 分页参数
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,

            // 字符串字段：模糊搜索（非空时生效）
            @RequestParam(value = "nickName", defaultValue = "") String nickName,
            @RequestParam(value = "loginName", defaultValue = "") String loginName,
            @RequestParam(value = "email", defaultValue = "") String email,
            @RequestParam(value = "role", defaultValue = "") String role,

            // 数值字段（score为int类型）：支持精确匹配和范围查询
            @RequestParam(value = "score", required = false) Integer score, // 精确匹配
            @RequestParam(value = "minScore", required = false) Integer minScore, // 最小值（>=）
            @RequestParam(value = "maxScore", required = false) Integer maxScore // 最大值（<=）
    ) {
        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> qw = new QueryWrapper<>();

        // 1. 字符串字段：模糊搜索（仅当参数非空时添加条件）
        if (StringUtils.hasText(nickName)) {
            qw.lambda().like(User::getNickName, nickName);
        }
        if (StringUtils.hasText(loginName)) {
            qw.lambda().like(User::getLoginName, loginName);
        }
        if (StringUtils.hasText(email)) {
            qw.lambda().like(User::getEmail, email);
        }
        if (StringUtils.hasText(role)) {
            qw.lambda().eq(User::getRole, role); // 若角色是枚举，建议用eq()精确匹配
        }

        // 2. 数值字段（score）：支持精确匹配和范围查询
        if (score != null) {
            // 精确匹配：score等于指定值
            qw.lambda().eq(User::getScore, score);
        } else {
            // 范围查询：minScore（>=）和maxScore（<=）可单独或组合使用
            if (minScore != null) {
                qw.lambda().ge(User::getScore, minScore); // greater than or equal
            }
            if (maxScore != null) {
                qw.lambda().le(User::getScore, maxScore); // less than or equal
            }
        }
        // 排序：按ID降序
        qw.lambda().orderByDesc(User::getId);

        // 执行查询
        Page<User> resultPage = userService.page(page, qw);
        return Result.success(resultPage);
    }*/

    /**
     * 获取用户列表，一个参数
     */
    @GetMapping("/lists2")
    public Result<?> list2(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "2") int pageSize,
            @RequestParam(value = "search", defaultValue = "") String search) {
        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda().like(!search.isEmpty(), User::getNickName, search)//模糊查询
                .or()
                .like(!search.isEmpty(), User::getLoginName, search)
                .or()
                .like(!search.isEmpty(), User::getEmail, search)
                .or()
                .like(!search.isEmpty(), User::getRole, search)
                .or()
                .like(!search.isEmpty(), User::getScore, search)
                .orderByDesc(User::getId);

        return Result.success(userService.page(page, qw));
    }

    //用户更新头像
    @PostMapping("/avatar/update")
    public Result<?> updateAvatar(@RequestParam("avatar") MultipartFile avatar) throws IOException {
        String fileName = userService.updateAvatar(avatar);
        return Result.success(fileName);
    }

}
